package com.warm.pump.frame.db.impl;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.fastjson.JSON;

import com.warm.pump.frame.db.DataSourceWrapper;
import com.warm.pump.module.work.bean.po.gen.WorkDb;
import org.apache.commons.collections.MapUtils;

import javax.sql.DataSource;
import java.util.Map;

/**
 * Created by guozj on 2017/10/12.
 */
public class DruidWrapper extends DataSourceWrapper {
    @Override
    public DataSource wrap(WorkDb db) throws Exception {

        String driverClassName = db.getDriverClass();
        String url = db.getDbUrl();
        String username = db.getDbUser();
        String password = db.getDbPassword();

        Map<String,Object> optionMap = JSON.parseObject(db.getPoolOptions());

        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setInitialSize(MapUtils.getInteger(optionMap, "initialSize", 3));
        dataSource.setMaxActive(MapUtils.getInteger(optionMap, "maxActive", 20));
        dataSource.setMinIdle(MapUtils.getInteger(optionMap, "minIdle", 1));
        dataSource.setMaxWait(MapUtils.getInteger(optionMap, "maxWait", 60000));
        dataSource.setTimeBetweenEvictionRunsMillis(MapUtils.getInteger(optionMap, "timeBetweenEvictionRunsMillis", 60000));
        dataSource.setMinEvictableIdleTimeMillis(MapUtils.getInteger(optionMap, "minEvictableIdleTimeMillis", 300000));
        dataSource.setTestWhileIdle(MapUtils.getBoolean(optionMap, "testWhileIdle", true));
        dataSource.setTestOnBorrow(MapUtils.getBoolean(optionMap, "testOnBorrow", false));
        dataSource.setTestOnReturn(MapUtils.getBoolean(optionMap, "testOnReturn", false));
        dataSource.setMaxOpenPreparedStatements(MapUtils.getInteger(optionMap, "maxOpenPreparedStatements", 20));
        dataSource.setRemoveAbandoned(MapUtils.getBoolean(optionMap, "removeAbandoned", true));
        dataSource.setRemoveAbandonedTimeout(MapUtils.getInteger(optionMap, "removeAbandonedTimeout", 1800));
        dataSource.setLogAbandoned(MapUtils.getBoolean(optionMap, "logAbandoned", true));
        return dataSource;
    }
}
